<?php

declare(strict_types=1);

namespace App\Command;

use App\Constants\Consts;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\DbConnection\Db;
use Hyperf\Support\Filesystem\Filesystem;
use function Hyperf\Support\env;

require_once(BASE_PATH . '/app/Libs/Helper.php');

/**
 * 批量导入xml单词
 */
#[Command]
class SaveWordCommand extends HyperfCommand
{
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;

        // 定义命令行名称
        parent::__construct('save:word');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('批量保存xml单词');
    }

    public function handle()
    {
        $this->line('开始导入单词表');
        $fs = new Filesystem();
        $dbname = env('DB_DATABASE', '');
        $table = 'words';
        $res = Db::select("SELECT table_name FROM information_schema.tables WHERE table_schema = '{$dbname}' and table_name='{$table}' limit 1");
        if (empty($res)) {
            $this->logger->error('请先导入单词表');
            return \Hyperf\Command\Command::FAILURE;
        }

        $wPath = BASE_PATH . Consts::WORDS_PATH;
        $num = Consts::WORDTXT_NUM;

        $sql = "select word from {$table} order by RAND() limit {$num}";
        $res = Db::select($sql);
        $str = '';
        foreach ($res as $row) {
            $str .= $row->word . PHP_EOL;
        }
        $fs->put($wPath, $str);

        $this->line('单词表已经全部生成，程序退出');
        return \Hyperf\Command\Command::SUCCESS;
    }
}
